package com.zhenwei.zscm.repo;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhenwei.zscm.common.base.UserContext;
import com.zhenwei.zscm.common.utils.Linq;
import com.zhenwei.zscm.entity.ExceptionLogEntity;
import com.zhenwei.zscm.mapper.IExceptionLogMapper;
import com.zhenwei.zscm.mappings.LogMapping;
import com.zhenwei.zscm.model.dto.log.ExceptionLogDTO;
import com.zhenwei.zscm.model.dto.user.UserDTO;
import com.zhenwei.zscm.model.vo.log.QueryExLogVO;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ExceptionLogRepo extends ServiceImpl<IExceptionLogMapper, ExceptionLogEntity> {

    @Async
    public void createAsync(String logType, String exMessage, String exStackTrace) {
        UserDTO currentUser = UserContext.getCurrentUser();

        var e = new ExceptionLogEntity();
        e.setExMessage(exMessage);
        e.setExStackTrace(exStackTrace);
        e.setLogType(logType);
        e.setLogTime(new Date());
        e.setLogUser(currentUser == null ? "" : currentUser.getUserName());
        e.setLogUserId(currentUser == null ? "" : currentUser.getGuid());

        this.save(e);
    }

    public List<ExceptionLogDTO> list(QueryExLogVO query){
        var q = new LambdaQueryWrapper<ExceptionLogEntity>();
        q.eq(StrUtil.isNotBlank(query.getLogType()), ExceptionLogEntity::getLogType, query.getLogType());
        q.like(StrUtil.isNotBlank(query.getExMessage()), ExceptionLogEntity::getExMessage, query.getExMessage());
        q.ge(query.getLogTimeStart() != null, ExceptionLogEntity::getLogTime, query.getLogTimeStart());
        q.le(query.getLogTimeEnd() != null, ExceptionLogEntity::getLogTime, query.getLogTimeEnd());

        q.orderByDesc(ExceptionLogEntity::getId);
        var p = new Page<ExceptionLogEntity>(query.getPageNo(), query.getPageSize(), true);
        var page =this.page(p,q);
        query.setTotalCount(page.getTotal());
        var list = page.getRecords();
        return Linq.mapList(list, LogMapping.INSTANCE::entity2Dto);
    }

    public List<String> getLogTypes(){
        var q = new LambdaQueryWrapper<ExceptionLogEntity>();
        q.groupBy(ExceptionLogEntity::getLogType);
        q.select(ExceptionLogEntity::getLogType);
        q.orderByAsc(ExceptionLogEntity::getLogType);
        List<ExceptionLogEntity> list = this.list(q);
        return Linq.mapList(list, ExceptionLogEntity::getLogType);
    }
}
